package com.letoken.platform.pub.configuration;

import com.letoken.platform.pub.interceptor.CustomizeLocaleChangeInterceptor;
import com.letoken.platform.pub.message.LocaleMessage;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.annotation.Resource;
import java.util.Locale;

/**
 * @author wyl
 * @Description 国际化消息返回拦截器
 * @date 2023/1/5 14:41
 * @Version 1.0
 */
@Configuration
public class LocaleChangeConfiguration implements WebMvcConfigurer {

    @Resource
    private CustomizeLocaleChangeInterceptor customizeLocaleChangeConfiguration;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        customizeLocaleChangeConfiguration.setParamName("language");
        registry.addInterceptor(customizeLocaleChangeConfiguration);
    }

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        //指定默认语言
        localeResolver.setDefaultLocale(Locale.CHINA);
        return localeResolver;
    }

    @Bean("resultCodeMessageResource")
    public MessageSource resultCodeMessageResource() {
        ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
        //指定国际化的Resource Bundle地址
        resourceBundleMessageSource.setBasename("static/i18n/message");
        //指定国际化的默认编码
        resourceBundleMessageSource.setDefaultEncoding("UTF-8");
        return resourceBundleMessageSource;
    }

    @Bean("resultCodeLocaleMessage")
    public LocaleMessage resultCodeLocaleMessage() {
        return new LocaleMessage(resultCodeMessageResource());
    }

}
